<?php
require __DIR__ . '/../bootstrap.php';

use Service\UserManager;

$em = require __DIR__ . '/../example/em.php';

$manager = new UserManager($em);

if (isset($_POST['get_agent']) and $_POST['get_agent'] == 'Y') {
    $idUser = 1;
    $manager = new UserManager($em);
    $user = $manager->getEntity($idUser);
    $childrens = $user->getChildren();
    $html = "";
    foreach ($childrens as $children) {
        $html .= '<option value="' . $children->getId() . '">' . $children->getFullName() . '</option>';
    }
    echo $html;
    exit();
}

if (!$manager->isValidUserName($_POST['u_username'])) {
    echo '{ "message": "Юзер с таким логином существует", "type": "st-error" }';
    exit();
}
/*
if (!$manager->isValidUserEmail($_POST['u_email'])) {
    echo '{ "message": "Такой E-mail уже существует", "type": "st-error" }';
    exit();
}
*/
$parent = $_POST['u_parent'];
$data = array(
    'group' => $_POST['u_group'],
    'name' => $_POST['u_username'],
    'parent' => $parent,
    'fullName' => $_POST['u_name'],
    'password' => md5($_POST['u_password']),
    'email' => $_POST['u_email'],
    'balance' => 0,
    'bonus' => 1
);

$user = $manager->create($data);

require_once('../lib/PHPMailer_5.2.4/class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"

$body = 'Создан новый аккаунт в системе agent.smart-sim.ru' . "\n";
$body .= 'Ваш логин: ' . $user->getName() . ' (Используется для входа в систему)' . "\n";
$body .= 'Ваше имя: ' . $user->getFullName() . "\n";
$body .= 'Ваш e-mail: ' . $user->getEmail() . "\n";
//$body .= 'Группа: ' . print_r($user->getGroup()) . "\n";
$body .= 'Ваш пароль: ' . $_POST['u_password'] . "\n";

$mail->AddReplyTo("partners@smart-sim.ru", "");

$mail->SetFrom('partners@smart-sim.ru', '');

$mail->AddReplyTo("partners@smart-sim.ru", "");

//Кому
$address = $user->getEmail();

//Кому
$mail->AddAddress($address, $user->getName());
$mail->Subject = "Создан новый пользователь на Agent SmartSim";

//Копия
$mail->AddCC('partners@smart-sim.ru', 'partners@smart-sim.ru');
$mail->AddCC('makerra@gmail.com', 'Paul Kamotsky');
$mail->AddCC('kerch@inbox.ru', 'kerch@inbox.ru');

//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->CharSet = 'UTF-8';
$mail->ContentType = 'text/plain';
$mail->IsHTML(false);
$mail->Body = $body;
//$mail->AddAttachment("lib/PHPMailer_5.2.4/examples/images/phpmailer.gif");      // attachment
//$mail->AddAttachment("lib/PHPMailer_5.2.4/examples/images/phpmailer_mini.gif"); // attachment

if (!$mail->Send()) {
    echo '{ "message": "Ошибка! ' . $mail->ErrorInfo . '", "type": "st-error" }';
} else {
    echo '{ "message": "Создан Юзер ' . $user->getName() . " id: " . $user->getId() . '", "type": "st-success" }';
}

